package cn.zs.supply.common.core.web.config;

import cn.zs.supply.common.core.web.filter.TraceFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import brave.Tracer;

public class BaseFilterConfig {
    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${global.workerId}")
    private long workerId = 1;
    @Autowired
    private Tracer tracer;

    public void setTracer(Tracer tracer) {
        this.tracer = tracer;
    }

    /**
     * 配置用户数据过滤器，实现用户信息的注入
     *
     * @return
     * @throws Exception
     */
    @Bean
    public FilterRegistrationBean userDataFilterRegistration() throws Exception {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        TraceFilter traceFilter = new TraceFilter();
        registration.addInitParameter("userDataKey", "userInfo");
        traceFilter.setTracer(tracer);
        registration.addInitParameter("serviceName", applicationName + ":" + workerId);
        //注入过滤器
        registration.setFilter(traceFilter);
        //拦截规则
        registration.addUrlPatterns("/*");
        //过滤器名称
        registration.setName("TraceFilter");
        //是否自动注册
        registration.setEnabled(true);
        //过滤器顺序
        registration.setOrder(1);
        return registration;
    }
}
